package com.zhku.zhny.admin.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.zhku.zhny.admin.exception.SearchException;
import com.zhku.zhny.admin.service.AdminService;
import com.zhku.zhny.admin.service.AdminServiceImpl;
import com.zhku.zhny.domain.Admin;
import com.zhku.zhny.util.BaseServlet;
import com.zhku.zhny.util.MD5Util;

@WebServlet("/admin")
public class AdminServlet extends BaseServlet{
	
	private static final long serialVersionUID = 1L;
	
	private static Map<String, Admin>info = new HashMap<String, Admin>();
	
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String adminName = request.getParameter("adminName");
		String password = request.getParameter("password");
		AdminService adminService = new AdminServiceImpl();
		try {
			Admin admin = adminService.login(adminName, password);
			if(admin != null) {
				String key = MD5Util.md5(admin.getAdminId());
				info.put(key, admin);
				response.getWriter().print(key);
			}else {
				response.getWriter().print("");
			}
		} catch (SearchException e) {
			e.printStackTrace();
			response.getWriter().print("");
		}
	}
	
	public void getAdminInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String key = request.getParameter("key");
		Admin admin = info.get(key);
		if(admin!=null) {
			String data = JSON.toJSONString(admin);
			response.getWriter().print(data);
		}else {
			response.getWriter().print("");
		}
	}
	
	public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String key = request.getParameter("key");
		if(info.containsKey(key)) {
			info.remove(key);
			response.getWriter().print("true");
		}else {
			response.getWriter().print("false");
		}
	}
}
